// JavaScript code - The Grizzlies Tank
// Midpoint Displacement algorithm

function app() { //all javascript code goes within this function
    var points = new Array(); //the array where Y coordinates are stored
    /* PARAMETERS */
    noS = 80; //set the number of final segments
    mD = 180; //the maximum displacement of Y coordinate
    minY = 40 //minimum value of Y coordinate
    maxY = 340 //maximum value of Y coordinate
    points[0] = Math.random() * (maxY - minY) + minY; //any random number between minY and maxY
    points[noS] = Math.random() * (maxY - minY) + minY; //any random number between minY and maxY
     
    reduction = 0.4; //the amount to which mD is reduced at each iteration (it should be between 0 and 1)
    
    /* MIDPOINT DISPLACEMENT FUNCTION */

    function midpoint(start, end, mD, reduction) {
        var middle = Math.round((start + end) / 2);
        if ((end - start <= 1) || middle == start || middle == end) {
            return;
        }
        
        /* this is a good example of when do while loop is useful
        the loop avoids to have Y values out of the 40-340 range */
        
        do { 
            var nY = (points[end] + points[start]) / 2 + mD * (1 - 2 * Math.random());
        } while (nY<minY || nY>maxY)
        points[middle] = nY;
        midpoint(start, middle, mD * reduction, reduction);
        midpoint(middle, end, mD * reduction, reduction);
    }

    /* CANVAS */

    function drawTerrain() {
        var theCanvas = document.getElementById("canvasOne"); //reference to canvas element
        var context = theCanvas.getContext("2d"); //get the reference to canvas context
        context.beginPath(); //begin the path
        x = 0;
        y = 480
        context.moveTo(x, y); //move the "pencil" to the left-bottom corner of the canvas
        context.lineTo(0, points[0]); //draw a line from the previous position of the "pencil" to the position defined in the arguments (in this case to the Y coordinate )
/* here goes some code (10 lines of code are more than enough):
                    - loop through the array values you generate before
                    - for each value calculate the implicit X coordinate (according to the number of segments)
                    - move the pencil to the new X,Y coordinates */

        for (i = 0; i < noS+1; i++) {
            xt = Math.round(i*640/noS);
            yt = 480 - points[i];
            context.lineTo(xt, yt);
        }
        context.lineTo(640, 480);
        context.closePath(); //close the path
        context.fillStyle = "#008800"; //define fill color
        context.fill(); //fill the path with the color specified
    }

    midpoint(0, noS, mD, reduction); //call to midpoint displacement function
    drawTerrain(); //call to draw terrain function
}
